package com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Node;

import com.michaelwolf.mytool.wcfcompmanger.wcfanalyzer.WCFLoader.TraverseCacheData;

public class ScriptFileReferFounder {
	
	public final static Pattern groovyID = Pattern.compile("\\.invoke.*\\(['|\"](system:[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*)['|\"]");

	public static void foundRef(File[] scriptFiles,
			TraverseCacheData traverseCacheData) {
		if(scriptFiles == null) 
			return;
		
		Map<String, Node> componentIdMap = traverseCacheData.getComponentIdMap();
		Map<Node, Set<Node>> scriptReferMap = traverseCacheData.getScriptReferMap();
		
		FileReader fr = null;
		BufferedReader fbr = null;
		for(File scriptFile : scriptFiles){
			try {
				fr = new FileReader(scriptFile);
				fbr = new BufferedReader(fr);
				
				while(fbr.ready()){
					String scriptLine = fbr.readLine();
					Matcher macher = groovyID.matcher(scriptLine);
					if(macher.find()){
						String referID = macher.group(1);
						Node referScriptNode = componentIdMap.get(referID);
						Set<Node> fileNodeSet;
						if(scriptReferMap.containsKey(referScriptNode)){
							fileNodeSet = scriptReferMap.get(referScriptNode);
							
						}else{
							fileNodeSet = new HashSet<>();
							scriptReferMap.put(referScriptNode, fileNodeSet);
						}
						String scriptNodeID = getScriptNodeID(scriptFile);
						Node scriptNode = componentIdMap.get(scriptNodeID);
						fileNodeSet.add(scriptNode);
						
					}
				}
				
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					fbr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	
	
	private static String getScriptNodeID(File scriptFile) {
		String fileName = scriptFile.getName();
		String scriptId = fileName.substring(0, fileName.indexOf("."));
		String moduleName = scriptFile.getParentFile().getParentFile().getName();
		
		return "system:" + moduleName + "." + scriptId;
	}


	//public final static Pattern groovyID = Pattern.compile("functionHelper\\.invoke.*(system:.*)");
	public static void main(String[] args){
		getScriptNodeID(new File("C:\\src\\storage\\wcf\\StorageBase\\system\\storage_afport\\scripts\\sanFnCreatePortTopologyTableInput.groovy"));
	}

}
